package oakclub.service;

import oakclub.global.Container;
import oakclub.utility.EncryptUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AuthService
{
    private final Logger logger = LoggerFactory.getLogger(AuthService.class);

    public long authToken() throws Exception
    {
        // fb token
        FacebookService facebookService = (FacebookService) Container.getComponent(FacebookService.class);
        String fbToken = facebookService.getToken();

        // auth by cache
        MemcachedService memcachedService = (MemcachedService) Container.getComponent(MemcachedService.class);
        String keyId = EncryptUtility.encrypt(fbToken, EncryptUtility.HashType.SHA1);
        Long cache = null;
        try
        {
            cache = (Long) memcachedService.get(MemcachedService.Key.FB_TOKEN, keyId);
        }
        catch(Exception e)
        {
            this.logger.warn("memcached issue", e);
        }
        if(cache != null)
        {
            long userId = cache.longValue();
            return userId;
        }

        // auth by fb
        long userId = facebookService.getUserId();
        cache = Long.valueOf(userId);
        try
        {
            memcachedService.set(MemcachedService.Key.FB_TOKEN, keyId, cache);
        }
        catch(Exception e)
        {
            this.logger.warn("memcached issue", e);
        }

        return userId;
    }
}
